package org.sith.taskrunner.servlets;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.zip.GZIPOutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.sith.taskrunner.api.exceptions.TaskExecutionException;
import org.sith.taskrunner.api.exceptions.TaskInitException;
import org.sith.taskrunner.api.exceptions.TransformInputDataException;
import org.sith.taskrunner.ejb.tasks.SumInputData;
import org.sith.taskrunner.ejb.tasks.SumResult;
import org.sith.taskrunner.ejb.tasks.SumTask;
import org.sith.taskrunner.ejb.transformers.StringSumDataTransformer;
import org.sith.taskrunner.ejb.transformers.StringXmlTransformer;

/**
 * Servlet implementation class SumTaskServlet
 */
public class SumTaskServlet extends HttpServlet {



    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");        

        PrintWriter out;
        String acceptEncoding = request.getHeader("accept-encoding");
		if((acceptEncoding!=null)&&(acceptEncoding.indexOf("gzip")!=-1)){
			out = new PrintWriter(new GZIPOutputStream(response.getOutputStream()), false);
			response.setHeader("content-encoding", "gzip");
		}else{
			out = response.getWriter();
		}
        try {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Number sum</title>");
            out.println("</head>");
            out.println("<body bgcolor=#aabbff>");
            out.println("<h2>Enter the natural numbers through gap:</h2><p><p>");
            out.println("<form name=form1 method=get>");
            out.println("<input type=text name=data>");
            out.println("<input type=submit value=Send>");
            out.println("<form>");
            String data = request.getParameter("data");
            makeTaskAndPrintResult(out, data);
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }

    }


    private void makeTaskAndPrintResult(PrintWriter out, String data) {
    	Integer sumResult;
        if (data != null) {
            try {
                StringSumDataTransformer transformer = new StringSumDataTransformer();
                SumInputData sumInputData = transformer.transform(data);
                SumTask task = new SumTask();
                task.init(sumInputData);
                SumResult result = task.executeTask();
                sumResult = result.getResult();
                if (data.length() != 0)
                    out.println("<h2>Sum result: "
                            + Double.toString(sumResult) + "</h2><p><p>");
            } catch (TaskExecutionException e) {
                printError(out, e);
            } catch (TaskInitException e) {
                printError(out, e);
            } catch (TransformInputDataException e) {
                 printError(out, e);
            }
        }
    }

    private void printError(PrintWriter out, Exception e) {
        out.println("<p style=\"color:red\">" + e.getLocalizedMessage() + "<p>");
    }

   

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
    	response.setContentType("text");
		String data = request.getParameter("data");
		PrintWriter out = response.getWriter();
		try {
			if (data != null) {
				StringXmlTransformer xmlParser = new StringXmlTransformer();
				InputStream input = new ByteArrayInputStream(data.getBytes());
				SumInputData inputData = xmlParser.transform(input);
				SumTask task = new SumTask();
				task.init(inputData);
				SumResult result = task.executeTask();
				out.println("Rezult is "+result.getResult());
			} else { 
				out.println("Send a values in XML");
			}
		} catch (TransformInputDataException e) {
			out.println(e.getLocalizedMessage());
		} catch (TaskInitException e) {
			out.println(e.getLocalizedMessage());
		} catch (TaskExecutionException e) {
			out.println(e.getLocalizedMessage());
		}
		out.close();
    }

}
